<template>
  <div class="background" :style="backgroundStyle">
<!--    <button @click="toggleBackgroundColor" class="toggle-button">{{ backgroundColor === 'white' ? '黑色' : '白色' }}</button>-->
  </div>
</template>

<script>
import { useImageStore } from '../stores/imageStore.js';
import { ref, computed, onMounted } from 'vue';

export default {
  setup() {
    const imageStore = useImageStore();
    const images = ref([]);
    const currentIndex = ref(0);
    const transitionDuration = 3500; // 过渡时间（毫秒）
    const imageCount = ref(0);
    const backgroundColor = ref('white'); // 初始背景颜色为白色

    const backgroundStyle = computed(() => ({
      backgroundImage: images.value.length ? `url(${images.value[currentIndex.value]})` : 'none',
      backgroundColor: backgroundColor.value === 'white' ? '#ffffff' : '#000000',
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat',
      transition: `background-image ${transitionDuration}ms ease-in-out, background-color 500ms ease-in-out`,
    }));

    onMounted(() => {
      // 从Pinia Store中获取图片数据
      images.value = imageStore.images;

      // 如果Pinia Store中没有图片数据，则初始化图片数据
      if (images.value.length === 0) {
        const initialImages = [
          '/src/static/image/1.jpg',
          '/src/static/image/2.jpg',
          '/src/static/image/3.jpg',
          '/src/static/image/4.jpg',
          '/src/static/image/5.jpg',
          '/src/static/image/6.jpg',
          '/src/static/image/7.jpg',
        ];
        imageCount.value = initialImages.length;
        initialImages.forEach(image => {
          fetch(image)
            .then(response => response.blob())
            .then(blob => {
              const reader = new FileReader();
              reader.onloadend = () => {
                const base64data = reader.result;
                imageStore.addImage(base64data);
                images.value.push(base64data);
                imageCount.value--;
                if (imageCount.value === 0) {
                  startCarousel();
                }
              };
              reader.readAsDataURL(blob);
            });
        });
      } else {
        startCarousel();
      }
    });

    const startCarousel = () => {
      setInterval(() => {
        currentIndex.value = (currentIndex.value + 1) % images.value.length;
      }, transitionDuration);
    };

    return {
      backgroundStyle,
      backgroundColor,
    };
  },
};
</script>

<style scoped>
.background {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
}

.toggle-button {
  position: absolute;
  top: 20px;
  right: 20px;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  z-index: 1;
}

.toggle-button:hover {
  background-color: #0056b3;
}
</style>
